package brainfsck

import chisel3._
import chisel3.util._

class PassthroughBuffer(xlen: Int) extends Module {
    val io = IO(new Bundle {
        val writePort = Flipped(Decoupled(UInt(xlen.W)))
        val readPort  = Decoupled(UInt(xlen.W))
    })

    val buffer = Reg(UInt(xlen.W))
    val bufferValid = RegInit(false.B)

    buffer := Mux(
        bufferValid,
        Mux(io.writePort.valid &&  io.readPort.ready, io.writePort.bits, buffer),
        Mux(io.writePort.valid && !io.readPort.ready, io.writePort.bits, buffer)
    )
    bufferValid := Mux(
        bufferValid,
        io.writePort.valid || !io.readPort.ready,
        io.writePort.valid && !io.readPort.ready
    )

    io.writePort.ready := !bufferValid || io.readPort.ready
    io.readPort.valid  := bufferValid || io.writePort.valid
    io.readPort.bits   := Mux(bufferValid, buffer, io.writePort.bits)
}
